from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU,GoodsCategory

from goods.models import Brand

from meiduo_admin.utils import PageNum

from meiduo_admin.serializers.spus import SPUSerializer

from meiduo_mall.apps.meiduo_admin.serializers.skus import GoodsCategorySerializer
from meiduo_admin.serializers.spus import BrandSerializer


class SPUView(ModelViewSet):
    # 指定查询集
    queryset = SPU.objects.all()
    # 指定序列化器
    serializer_class = SPUSerializer
    # 指定分页器
    pagination_class = PageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    @action(methods=['get'], detail=False)
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return SPU.objects.all()
        else:
            return SPU.objects.filter(name__contains = keyword)

    def brand(self, request):
        data = Brand.objects.all()
        ser = BrandSerializer(data, many=True)
        return Response(ser.data)

    def categories(self, request):
        data = GoodsCategory.objects.filter(parent=None)
        ser = GoodsCategorySerializer(data, many=True)
        return Response(ser.data)

    def simple(self, request,pk):
        data = GoodsCategory.objects.filter(parent=pk)
        ser = GoodsCategorySerializer(data, many=True)
        return Response(ser.data)

